package org.dromara.system.controller;

import java.util.List;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.api.model.LoginUser;
import org.dromara.system.domain.EmailAccount;
import org.dromara.system.domain.EmailTemplate;
import org.dromara.system.domain.SysUser;
import org.dromara.system.mapper.EmailTemplateMapper;
import org.dromara.system.mapper.SysUserMapper;
import org.dromara.system.service.IEmailAccountService;
import org.dromara.system.service.IEmailTemplateService;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.web.core.BaseController;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.system.domain.vo.EmailConfigVo;
import org.dromara.system.domain.bo.EmailConfigBo;
import org.dromara.system.service.IEmailConfigService;
import org.dromara.common.mybatis.core.page.TableDataInfo;

/**
 * 支付邮件配置
 * 前端访问路由地址为:/system/EmailConfig
 *
 * @author Gavino
 * @date 2025-01-13
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/EmailConfig")
public class EmailConfigController extends BaseController {

    private final IEmailConfigService emailConfigService;
    private final SysUserMapper sysUserMapper;
    private final EmailTemplateMapper emailTemplateMapper;
    private final IEmailAccountService emailAccountService;
    private final IEmailTemplateService emailTemplateService;

    /**
     * 查询支付邮件配置列表
     */
    @SaCheckPermission("system:EmailConfig:list")
    @GetMapping("/list")
    public TableDataInfo<EmailConfigVo> list(EmailConfigBo bo, PageQuery pageQuery) {
        return emailConfigService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出支付邮件配置列表
     */
    @SaCheckPermission("system:EmailConfig:export")
    @Log(title = "支付邮件配置", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(EmailConfigBo bo, HttpServletResponse response) {
        List<EmailConfigVo> list = emailConfigService.queryList(bo);
        ExcelUtil.exportExcel(list, "支付邮件配置", EmailConfigVo.class, response);
    }

    /**
     * 获取支付邮件配置详细信息
     *
     * @param configId 主键
     */
    @SaCheckPermission("system:EmailConfig:query")
    @GetMapping("/{configId}")
    public R<EmailConfigVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long configId) {
        return R.ok(emailConfigService.queryById(configId));
    }

    /**
     * 新增支付邮件配置
     */
    @SaCheckPermission("system:EmailConfig:add")
    @Log(title = "支付邮件配置", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody EmailConfigBo bo) {
        return toAjax(emailConfigService.insertByBo(bo));
    }

    /**
     * 修改支付邮件配置
     */
    @SaCheckPermission("system:EmailConfig:edit")
    @Log(title = "支付邮件配置", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody EmailConfigBo bo) {
        return toAjax(emailConfigService.updateByBo(bo));
    }

    /**
     * 删除支付邮件配置
     *
     * @param configIds 主键串
     */
    @SaCheckPermission("system:EmailConfig:remove")
    @Log(title = "支付邮件配置", businessType = BusinessType.DELETE)
    @DeleteMapping("/{configIds}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] configIds) {
        return toAjax(emailConfigService.deleteWithValidByIds(List.of(configIds), true));
    }

    /**
     * 获取邮件配置
     */
    @SaCheckPermission("system:EmailConfig:list")
    @GetMapping("/get")
    public R<?> get() {
        JSONObject data = new JSONObject();
        LoginUser loginUser = LoginHelper.getLoginUser();
        if(loginUser == null) {
            return R.fail("登录信息已失效，请重新登录");
        }

        //查询当前登录人邮件开关
        SysUser sysUser = sysUserMapper.selectById(loginUser.getUserId());
        data.put("emailFlag", sysUser.getEmailFlag() == null ? 0 : sysUser.getEmailFlag());

        //查询当前选中邮箱账号
        List<EmailAccount> accounts = emailAccountService.selectAgentAccountList(loginUser.getUserId(), null, null);
        data.put("accounts", accounts);

        //查询启用的订单提醒模板
        List<EmailTemplate> templates = emailTemplateService.selectAgentTemplateList(loginUser.getUserId(), 1, null);
        data.put("templates", templates);

        return R.ok(data);
    }

    /**
     * 保存邮件配置
     */
    @SaCheckPermission("system:EmailConfig:save")
    @PostMapping("/save")
    public R<?> save(@RequestBody JSONObject json) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if(loginUser == null) {
            return R.fail("登录信息已失效，请重新登录");
        }

        //更新开关
        Integer emailFlag = json.getInteger("emailFlag");
        if (emailFlag != null) {
            sysUserMapper.update(null,
                new LambdaUpdateWrapper<SysUser>()
                    .set(SysUser::getEmailFlag, emailFlag)
                    .eq(SysUser::getUserId, loginUser.getUserId()));
        }

        //更新邮箱账号类型
        List<Long> selectAct = json.getList("selectAct", Long.class);
        emailAccountService.updateAgentAccountAType(loginUser.getUserId(), null, 1, 0);
        if (!selectAct.isEmpty()) {
            emailAccountService.updateAgentAccountAType(loginUser.getUserId(), selectAct, null, 1);
        }

        //更新模板状态
        Long selectTemp = json.getLong("selectTemp");
        List<EmailTemplate> templates = emailTemplateService.selectAgentTemplateList(loginUser.getUserId(), 1, 1);
        templates.forEach(obj -> {
            EmailTemplate up = new EmailTemplate();
            up.setTemplateId(obj.getTemplateId());
            up.setStatus(0);
            emailTemplateMapper.updateById(up);
        });
        if (selectTemp != null) {
            EmailTemplate up = new EmailTemplate();
            up.setTemplateId(selectTemp);
            up.setStatus(1);
            emailTemplateMapper.updateById(up);
        }
        return R.ok();
    }
}
